" Author: Michael Hofmann <mhofmann@redhat.com>
" Description: Lint the shell code in .gitlab-ci.yml files
"
" based on sh/shellcheck.vim by w0rp <devw0rp@gmail.com>
"
call ale#Set('yaml_shellcheck_executable', 'cki_gitlab_yaml_shellcheck')
call ale#Set('yaml_shellcheck_options', '')

function! ale_linters#yaml#shellcheck#GetCommand(buffer) abort
    let l:options = ale#Var(a:buffer, 'yaml_shellcheck_options')
    return '%e'
    \   . (!empty(l:options) ? ' ' . l:options : '')
    \   . ' --stdin-filename %s'
    \   . ' -'
endfunction

function! ale_linters#yaml#shellcheck#Handle(buffer, lines) abort
    let l:pattern = '\v^([a-zA-Z]?:?[^:]+):(\d+):(\d+)?:? ([^:]+): (.+) \[([^\]]+)\]$'
    let l:output = []

    for l:match in ale#util#GetMatches(a:lines, l:pattern)
        if l:match[4] is# 'error'
            let l:type = 'E'
        elseif l:match[4] is# 'note'
            let l:type = 'I'
        else
            let l:type = 'W'
        endif

        let l:item = {
        \   'lnum': str2nr(l:match[2]),
        \   'type': l:type,
        \   'text': l:match[5],
        \   'code': l:match[6],
        \}

        if !empty(l:match[3])
            let l:item.col = str2nr(l:match[3])
        endif

        " If the filename is something like <stdin>, <nofile> or -, then
        " this is an error for the file we checked.
        if l:match[1] isnot# '-' && l:match[1][0] isnot# '<'
            let l:item['filename'] = l:match[1]
        endif

        call add(l:output, l:item)
    endfor

    return l:output
endfunction

call ale#linter#Define('yaml', {
\   'name': 'shellcheck',
\   'executable': {buffer -> ale#Var(buffer, 'yaml_shellcheck_executable')},
\   'command': function('ale_linters#yaml#shellcheck#GetCommand'),
\   'callback': 'ale_linters#yaml#shellcheck#Handle',
\})
